package com.gao.api.gate.quick.core.registry;

import java.util.Collection;
import java.util.concurrent.Executor;

/**
 * <p></p>
 *
 * @author gaoshuangwen
 * @since 2022/01/12 11:42
 */
public class ListenableRegistry<Node> extends SimpleRegistry<Node>{

    private final Executor executor;

    private ChangeTask task;

    public ListenableRegistry(Collection<Node> registry, Executor executor) {
        super(registry);
        this.executor = executor;
    }

    @Override
    public void onChanged(RegistryEvent event) {
        if(task != null){
            executor.execute(task);
        }
    }

    @Override
    public void bindChangeHandler(RegistryChangeHandler handler) {

        this.task = new ChangeTask(handler);

    }

    private static class ChangeTask implements Runnable{

        private final RegistryChangeHandler registryChangeHandler;

        public ChangeTask(RegistryChangeHandler registryChangeHandler) {
            this.registryChangeHandler = registryChangeHandler;
        }

        @Override
        public void run() {
            try {
                registryChangeHandler.onChanged();
            }catch (Exception e){
                // noop
            }
        }
    }

}
